//
//  Copyright iOSDeveloperTips.com All rights reserved.
//
 
#import <CommonCrypto/CommonDigest.h>
 
@implementation NSString(MD5)
 
- (NSString*)MD5
{
	// Create pointer to the string as UTF8
  const char *ptr = [self UTF8String];

 	// Create byte array of unsigned chars
  unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];

	// Create 16 bytes MD5 hash value, store in buffer
  CC_MD5(ptr, strlen(ptr), md5Buffer);

	// Convert unsigned char buffer to NSString of hex values
  NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
  for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) 
		[output appendFormat:@"%02x",md5Buffer[i]];

  return output;
}

- (NSString*)MD5_16
{
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    NSString * string =  [NSString stringWithFormat:
                          @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                          result[0], result[1], result[2], result[3],
                          result[4], result[5], result[6], result[7],
                          result[8], result[9], result[10], result[11],
                          result[12], result[13], result[14], result[15]
                          ];
    return [string substringWithRange:NSMakeRange(8, 16)];
}
 
@end